<template>
  <NavBar></NavBar>
  <div class="management-container">
    <div class="management-box">
      <div class="header-container">
        <div class="search-title">牛只管理</div>
        <el-button type="primary" @click="showAddDialog">添加牛只</el-button>
      </div>
      
      <el-form :model="form" @submit.prevent="handleSearch">
        <el-form-item>
          <el-input
              v-model="form.searchParam"
              placeholder="输入牛ID进行筛选..."
              style="max-width: 600px"
              class="input-with-select"
          >
            <template #append>
              <el-button type="primary" :icon="Search" native-type="submit" />
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <div class="filter-sort-container">
        <el-select v-model="sortField" placeholder="排序字段" @change="handleSort">
          <el-option label="默认排序" value="" />
          <el-option label="按牛ID排序" value="id" />
          <el-option label="按添加日期排序" value="createdAt" />
          <el-option label="按成本排序" value="cost" />
          <el-option label="按利润排序" value="profit" />
        </el-select>
        <el-select v-model="sortOrder" placeholder="排序方式" @change="handleSort">
          <el-option label="升序" value="asc" />
          <el-option label="降序" value="desc" />
        </el-select>
        <el-select v-model="statusFilter" placeholder="状态筛选" @change="handleFilter">
          <el-option label="全部" value="" />
          <el-option label="在栏" value="active" />
          <el-option label="已出栏" value="deleted" />
        </el-select>
      </div>

      <div v-loading="loading" class="table-container">
        <el-table
            :data="cattleData"
            style="width: 100%; height: 60vh;"
            empty-text="暂无牛只记录"
        >
          <el-table-column prop="id" label="牛ID" width="80" />
          <el-table-column prop="additionReason" label="添加原因" width="150" />
          <el-table-column prop="createdAt" label="添加日期" width="150">
            <template #default="{row}">
              {{ new Date(row.createdAt).toLocaleDateString() }}
            </template>
          </el-table-column>
          <el-table-column prop="cost" label="成本(元)" width="120" />
          <el-table-column v-if="hasDeletedCattle" prop="isDeleted" label="状态" width="100">
            <template #default="{row}">
              <el-tag :type="row.isDeleted ? 'info' : 'success'">
                {{ row.isDeleted ? '已出栏' : '在栏' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="hasDeletedCattle" prop="deletionReason" label="出栏原因" width="150" />
          <el-table-column v-if="hasDeletedCattle" prop="revenue" label="出栏收入(元)" width="120" />
          <el-table-column v-if="hasDeletedCattle" prop="profit" label="利润(元)" width="120">
            <template #default="{row}">
              <span :style="{ color: row.profit > 0 ? 'green' : 'red' }">{{ row.profit }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="hasDeletedCattle" prop="deletedAt" label="出栏日期" width="150">
            <template #default="{row}">
              {{ row.deletedAt ? new Date(row.deletedAt).toLocaleDateString() : '' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="120">
            <template #default="{row}">
              <el-button 
                v-if="!row.isDeleted" 
                type="danger" 
                size="small" 
                @click="handleDelete(row)"
              >
                出栏
              </el-button>
              <el-button 
                v-else 
                type="info" 
                size="small" 
                disabled
              >
                已出栏
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>

  <!-- 添加牛只对话框 -->
  <el-dialog v-model="addDialogVisible" title="添加牛只" width="30%">
    <el-form :model="newCattle" label-width="100px">
      <el-form-item label="牛名称" required>
        <el-input v-model="newCattle.name" placeholder="请输入牛名称"></el-input>
      </el-form-item>
      <el-form-item label="耳标编号" required>
        <el-input v-model="newCattle.earTag" placeholder="请输入耳标编号"></el-input>
      </el-form-item>
      <el-form-item label="添加原因" required>
        <el-input v-model="newCattle.additionReason" placeholder="如：购买、出生等"></el-input>
      </el-form-item>
      <el-form-item label="初始重量(kg)">
        <el-input-number v-model="newCattle.initialWeight" :precision="2" :step="0.1" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item label="获得成本(元)" required>
        <el-input-number v-model="newCattle.cost" :precision="2" :step="100" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item label="喂食状态">
        <el-switch v-model="newCattle.isFeed" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>
      <el-form-item label="牛只照片">
        <el-upload
          class="avatar-uploader"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handlePhotoChange"
          :before-upload="beforePhotoUpload">
          <img v-if="photoPreview" :src="photoPreview" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddCattle">确认</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 删除牛只对话框 -->
  <el-dialog v-model="deleteDialogVisible" title="删除牛只" width="30%">
    <p>您确定要删除ID为 {{ selectedCattle?.id }} 的牛只吗？</p>
    <el-form :model="deathCattle" label-width="100px">
      <el-form-item label="出栏原因" required>
        <el-input v-model="deathCattle.deletionReason" placeholder="如：出售、死亡等"></el-input>
      </el-form-item>
      <el-form-item label="出栏收入(元)" required>
        <el-input-number v-model="deathCattle.revenue" :precision="2" :step="100" :min="0"></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确认出栏</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, computed } from "vue";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
import NavBar from "@/components/NavBar.vue";
import { Search, Plus } from "@element-plus/icons-vue";
import $ from 'jquery';

export default {
  components: { NavBar },
  setup() {
    const store = useStore();
    const form = reactive({ searchParam: "" });
    const cattleData = ref([]);
    const allCattleData = ref([]); // 存储所有数据，用于筛选和排序
    const loading = ref(false);
    const sortField = ref("");
    const sortOrder = ref("asc");
    const statusFilter = ref("");
    
    // 上传相关
    const photoFile = ref(null);
    const photoPreview = ref('');
    
    // 添加牛只相关
    const addDialogVisible = ref(false);
    const newCattle = reactive({
      name: "",
      earTag: "",
      additionReason: "",
      initialWeight: 0,
      cost: 0,
      isFeed: 0,
      photo: ""
    });
    
    // 删除牛只相关
    const deleteDialogVisible = ref(false);
    const selectedCattle = ref(null);
    const deathCattle = reactive({
      cattleId: null,
      deletionReason: "",
      revenue: 0
    });
    
    // 判断是否有已删除的牛只
    const hasDeletedCattle = computed(() => {
      return allCattleData.value.some(cattle => cattle.isDeleted);
    });

    // 获取所有牛只数据
    const fetchAllCattle = async () => {
      loading.value = true;
      try {
        const resp = await store.dispatch("fetchAllCattleList", {
          token: store.state.user.token
        });
        
        if (resp.status === "success") {
          console.log(resp);
          allCattleData.value = resp.data;
          cattleData.value = resp.data;
        }
      } catch (error) {
        ElMessage.error("获取牛只数据失败");
      } finally {
        loading.value = false;
      }
    };

    // 搜索处理
    const handleSearch = () => {
      if (!form.searchParam.trim()) {
        cattleData.value = [...allCattleData.value];
        return;
      }
      
      const searchParam = form.searchParam.toLowerCase().trim();
      cattleData.value = allCattleData.value.filter(cattle => {
        return cattle.id.toString().includes(searchParam);
      });
      
      // 保持筛选和排序
      applyFiltersAndSort();
    };

    // 排序处理
    const handleSort = () => {
      if (!sortField.value) {
        handleSearch(); // 重置为搜索结果
        return;
      }
      
      cattleData.value.sort((a, b) => {
        let aValue = a[sortField.value];
        let bValue = b[sortField.value];
        
        // 日期类型特殊处理
        if (sortField.value === 'createdAt' || sortField.value === 'deletedAt') {
          aValue = aValue ? new Date(aValue).getTime() : 0;
          bValue = bValue ? new Date(bValue).getTime() : 0;
        }
        
        if (sortOrder.value === 'asc') {
          return aValue > bValue ? 1 : -1;
        } else {
          return aValue < bValue ? 1 : -1;
        }
      });
    };

    // 筛选处理
    const handleFilter = () => {
      if (!statusFilter.value) {
        handleSearch(); // 重置为搜索结果
        return;
      }
      
      const filtered = allCattleData.value.filter(cattle => {
        if (statusFilter.value === 'active') {
          return !cattle.isDeleted;
        } else if (statusFilter.value === 'deleted') {
          return cattle.isDeleted;
        }
        return true;
      });
      
      cattleData.value = filtered;
      
      // 如果有搜索条件，继续应用搜索
      if (form.searchParam.trim()) {
        handleSearch();
      }
      
      // 应用排序
      if (sortField.value) {
        handleSort();
      }
    };
    
    // 应用所有筛选和排序
    const applyFiltersAndSort = () => {
      if (statusFilter.value) {
        handleFilter();
      }
      if (sortField.value) {
        handleSort();
      }
    };
    
    // 显示添加对话框
    const showAddDialog = () => {
      // 重置表单
      Object.assign(newCattle, {
        name: "",
        earTag: "",
        additionReason: "",
        initialWeight: 0,
        cost: 0,
        isFeed: 0,
        photo: ""
      });
      photoPreview.value = '';
      photoFile.value = null;
      addDialogVisible.value = true;
    };
    
    // 在handleAddCattle方法中添加照片上传逻辑
    const handleAddCattle = async () => {
      // 基本验证
      if (!newCattle.name || !newCattle.earTag || !newCattle.additionReason || newCattle.cost <= 0) {
        ElMessage.error("请填写所有必填字段");
        return;
      }
      
      loading.value = true;
      try {
        // 如果有选择照片，先上传照片
        if (photoFile.value) {
          const formData = new FormData();
          formData.append('file', photoFile.value);
          
          // 上传照片 - 使用Promise确保等待上传完成
          const photoResp = await new Promise((resolve, reject) => {
            $.ajax({
              url: "http://localhost:7090/api/cattle/upload/photo",
              type: "POST",
              data: formData,
              processData: false,
              contentType: false,
              success: function(response) {
                resolve(response);
              },
              error: function(error) {
                reject(error);
              }
            });
          });
          
          if (photoResp.status === "success") {
            // 设置照片URL到牛只信息中
            newCattle.photo = photoResp.message;
            console.log("照片上传成功，URL:", photoResp.message);
          } else {
            ElMessage.error("照片上传失败: " + photoResp.message);
            loading.value = false;
            return;
          }
        }
        
        console.log("准备提交牛只信息，包含照片URL:", newCattle.photo);
        
        // 提交牛只信息 - 使用Promise确保等待提交完成
        const resp = await new Promise((resolve, reject) => {
          $.ajax({
            url: store.state.cattle.apiEndpoints.add,
            type: "POST",
            headers: {
              Authorization: `Bearer ${store.state.user.token}`,
              "Content-Type": "application/json"
            },
            data: JSON.stringify(newCattle),
            success: function(response) {
              resolve(response);
            },
            error: function(error) {
              reject(error);
            }
          });
        });
        
        if (resp.status === "success") {
          ElMessage.success("添加牛只成功");
          addDialogVisible.value = false;
          await fetchAllCattle(); // 刷新列表
          
          // 重置表单
          Object.assign(newCattle, {
            name: "",
            earTag: "",
            additionReason: "",
            initialWeight: 0,
            cost: 0,
            isFeed: 0,
            photo: ""
          });
          photoFile.value = null;
          photoPreview.value = "";
        } else {
          ElMessage.error("添加失败: " + resp.message);
        }
      } catch (error) {
        console.error("添加牛只出错:", error);
        ElMessage.error("添加失败，请检查网络连接");
      } finally {
        loading.value = false;
      }
    };
    
    // 处理照片变更
    const handlePhotoChange = (file) => {
      photoFile.value = file.raw;
      photoPreview.value = URL.createObjectURL(file.raw);
    };
    
    // 照片上传前的验证
    const beforePhotoUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 5;
    
      if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 5MB!');
      }
      return isJPG && isLt2M;
    };
    
    // 显示删除对话框
    const handleDelete = (cattle) => {
      selectedCattle.value = cattle;
      deathCattle.cattleId = cattle.id;
      deathCattle.deletionReason = "";
      deathCattle.revenue = 0;
      deleteDialogVisible.value = true;
    };
    
    // 确认删除
    const confirmDelete = async () => {
      // 表单验证
      if (!deathCattle.deletionReason.trim()) {
        ElMessage.warning("请输入出栏原因");
        return;
      }
      
      loading.value = true;
      try {
        const resp = await store.dispatch("deleteCattle", {
          deathCattle: deathCattle,
          token: store.state.user.token
        });
        
        if (resp.status === "success") {
          ElMessage.success("牛只已成功出栏");
          deleteDialogVisible.value = false;
          await fetchAllCattle(); // 重新获取数据
        }
      } catch (error) {
        ElMessage.error("出栏操作失败");
      } finally {
        loading.value = false;
      }
    };

    onMounted(() => {
      fetchAllCattle();
    });

    return {
      form,
      cattleData,
      loading,
      sortField,
      sortOrder,
      statusFilter,
      hasDeletedCattle,
      handleSearch,
      handleSort,
      handleFilter,
      
      // 添加相关
      addDialogVisible,
      newCattle,
      photoPreview,
      showAddDialog,
      handleAddCattle,
      beforePhotoUpload,
      handlePhotoChange,
      
      // 删除相关
      deleteDialogVisible,
      selectedCattle,
      deathCattle,
      handleDelete,
      confirmDelete,
      
      Search,
      Plus
    };
  }
};
</script>

<style scoped>
.management-container {
  padding: 20px;
  min-height: calc(100vh - 56px);
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
}

.management-box {
  width: 90%;
  max-width: 1400px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.filter-sort-container {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.table-container {
  margin-top: 20px;
}

.symptoms-text {
  display: inline-block;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .management-box {
    width: 95%;
    padding: 15px;
  }
}

@media (max-width: 768px) {
  .management-container {
    padding: 10px;
  }
  
  .management-box {
    width: 100%;
    border-radius: 0;
  }
  
  .filter-sort-container {
    flex-direction: column;
  }
}

.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}
</style>